<?php
namespace app\api\controller;

use app\api\model\Configs;
use app\BaseController;


use app\model\admin\OrderItem;
use app\model\common\User as UserModel;
use app\model\common\UserWallet;
use app\model\common\UserWalletLog;
use dh2y\qrcode\QRcode;
use think\App;
use think\facade\Db;
use think\Image;
use think\Request;


use app\model\common\Web;


class Base extends BaseController
{
    // 是否自动实例化当前模型
    protected $autoNewModel = true;

    // 自定义实例化模型位置
    protected $ModelPath = null;

    // 实例化当前模型
    protected $M = null;

    // 是否开启自动验证
    protected $autoValidateCheck = true;

    // 不需要验证的方法
    protected $excludeValidateCheck = [];

    // 验证场景配置
    protected $autoValidateScenes = [];

    // 当前控制器信息
    protected $Cinfo = [];

    // 所属应用名称
    protected $modulePath = 'app\\api\\';

    protected $pageSize = 10;

//    protected $appId = 'wx41635aa32036a5d2';
//    protected $ghOriId = 'gh_aae6c55011bf';
//    protected $ghStaticUrl = 'https://msyp4-3gw78w4g4cdea401-1320072463.tcloudbaseapp.com/jump_mp.html';

//    protected $pigAmount = 5000;

    /**
     * 1. 自动实例化当前model
     */
    public function __construct(Request $request)
    {
        // 初始化控制器相关信息
        $this->initControllerInfo($request);
        // 实例化当前模型
        $this->getCurrentModel();
        // 自动验证
        $this->autoValidateAction();
    }

    // 初始化控制器相关信息
    public function initControllerInfo($request)
    {
//        dd($request);
        $str = $request->controller();
        // 获取真实控制器名称
        //  $arr = explode('.',$str);
        //  $Cname = $arr[count($arr)-1];
        $this->Cinfo = [
            'Cname' => class_basename($this),
            'Cpath' => str_replace('.', '\\', $str),
            // 当前方法
            'action' => $request->action()
        ];
//        dd($this->Cinfo);
    }

    // 获取当前模型实例
    public function getCurrentModel()
    {
        if (!$this->M && $this->autoNewModel) {
            $model = $this->ModelPath ? $this->ModelPath : $this->Cinfo['Cpath'];
            $this->M = app($this->modulePath . 'model\\' . $model);
        }
    }

    // 自动化验证
    public function autoValidateAction()
    {
        // app地址
        define('__APP_PATH__', __DIR__ . '/../../');

        $action = $this->Cinfo['action'];
        // 判断是否需要验证
        if ($this->autoValidateCheck && !in_array($action, $this->excludeValidateCheck)) {
            // 获取验证实例
//            $validateName = file_exists(__APP_PATH__ . 'validate/' . $this->Cinfo['Cpath'] . '.php') ? $this->Cinfo['Cpath'] : $this->Cinfo['Cname'];
//            $validate = app('app\api\validate\\' . $validateName);

            $validate = app('app\\api\\validate\\' . $this->Cinfo['Cname']);
            // 获取验证场景
            $scene = $action;
            if (array_key_exists($action, $this->autoValidateScenes)) {
                $scene = $this->autoValidateScenes[$action];
            }
            // 开始验证
            $params = request()->param();
            if (!$validate->scene($scene)->check($params)) {
                // 抛出异常
//                dd($validate->getError());
                ApiException($validate->getError());
            }
        }
    }

    //生成图片方法
    public function generateImage($userId, $inviteCode){
        $code = new QRcode();
        $path = 'uploads/qrcode/' . $userId . '.png';
        $url = 'https://h5.shangping.cc/pages/v2/register/register?invite_code=' . $inviteCode;
        $res = $code->png($url, $path, 15, QR_ECLEVEL_H);
        // 返回二维码的 URL，以便在后续操作中使用
        return $path;
    }

    //生成图片方法
    public function generateImageByMerchant($merchantId){
        $code = new QRcode();
        $path = 'uploads/merchant/qrcode/' . $merchantId . '.png';
        $url = '/pages/v2/merchant/settlement?merchant_id=' . $merchantId;
        $res = $code->png($url, $path, 15, QR_ECLEVEL_H);
        // 返回二维码的 URL，以便在后续操作中使用
        return \app\model\Base::getLocalUrl() . '/' . $path . '?t=' . time();
    }

    //合成邀请码
    public function merge($userId, $inviteCode, $qrcodePath)
    {
        $logoUrl = 'static/invite-bg.jpg';
        $text = '邀请码:' . $inviteCode;
        $textColor = '#000000';

        $qrCodeImg = Image::open($logoUrl);
        $qrCodeImg->water($qrcodePath, [600, 1500]);

        // 在二维码上添加文字
        $qrCodeImg->text($text, 'static/shangshouguomeiti.ttf', 80, $textColor, [640, 900]);
//        $qrCodeImg->text($text, '', 20, $textColor, [0, 0]);

        // 保存新的图片到服务器上的一个文件
        $mergedFile = 'uploads/poster/' . $userId . '.png';  // 合成后的文件名
        $qrCodeImg->save($mergedFile);

        return \app\model\Base::getLocalUrl() . '/' . $mergedFile . '?t=' . time();
//        return showSuccess(['image_url'=>\app\model\Base::getLocalUrl() . '/' . $mergedFile]);
    }


//
//    //自定义验证
//    public static function customValidateAction($validateName, $scene, $params)
//    {
//        $validate = app('app\validate\\' . $validateName);
//        // 开始验证
//        if (!$validate->scene($scene)->check($params)) {
//            // 抛出异常
//            ApiException($validate->getError());
//        }
//    }
//
//    //新增模式逻辑
//
//
//    public function batchInsert($table, $list)
//    {
//        //这里假设arr的key和数据库字段同步，其实大多数框架中在php操作数据库的时候都是这么设计的
//        $arr = $list[0];
//        $arr_keys = array_keys($arr);
////        print_r($arr_keys);die;
//        $sql = 'INSERT INTO `' . $table . '` (`' . implode('`,`', $arr_keys) . '`) values';
//        foreach ($list as $item) {
//            $arr_values = array_values($item);
////            print_r($arr_values);die;
//            $sql .= " ('" . implode("','", $arr_values) . "'),";
//        }
//        $sql = substr($sql, 0, -1);
//        return $sql;
//    }
//
//
//    /**
//     * 批量更新函数，返回批量更新执行的sql
//     * @param string $table 要更新的表名，例：goods表
//     * @param array $data 待更新的数据，二维数组格式，例：$data = [['id' => 1, 'name' => 'zhangsan'],['id' => 2, 'name' => 'lisi']];
//     * @param string $field string 值不同的条件，例：id
//     * @param array $params where条件的其他额外判断条件，键值对应的一维数组，例：['parent_id' => 1]
//     * @return bool|string
//     */
//    public function batchUpdate($table = '', $data = [], $field = '', $params = [])
//    {
//        if (!is_array($data) || !$field || !is_array($params)) {
//            return false;
//        }
//
//        $updates = $this->parseUpdate($data, $field);
//        $where = $this->parseParams($params);
//
//        // 获取所有键名为$field列的值，值两边加上单引号，保存在$fields数组中
//        $fields = array_column($data, $field);
//        $fields = implode(',', array_map(function ($value) {
//            return "'" . $value . "'";
//        }, $fields));
//
//        $sql = sprintf("UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $table, $updates, $field, $fields, $where);
//        return $sql;
//    }
//
//    /**
//     * 将二维数组转换成CASE WHEN THEN的批量更新条件
//     * @param $data array 二维数组
//     * @param $field string 列名
//     * @return string sql语句
//     */
//    public function parseUpdate($data, $field)
//    {
//        $sql = '';
//        $keys = array_keys(current($data));
//        foreach ($keys as $column) {
//            if ($column == $field) {
//                continue;
//            }
//            $sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);
//            foreach ($data as $line) {
//                $sql .= sprintf("WHEN '%s' THEN '%s' \n", $line[$field], $line[$column]);
//            }
//            $sql .= "END,";
//        }
//        return rtrim($sql, ',');
//    }
//
//    /**
//     * 解析where条件
//     * @param $params
//     * @return array|string
//     */
//    public function parseParams($params = [])
//    {
//        $where = [];
//        if (!empty($params)) {
//            foreach ($params as $key => $value) {
//                $where[] = sprintf("`%s` = '%s'", $key, $value);
//            }
//        }
//        return !empty($where) ? ' AND ' . implode(' AND ', $where) : '';
//    }
//
//    //所有计算佣金的逻辑
//    public function calCommission($userId, $parentId, $orderId)
//    {
//        $userInfo = Db::name('user')->find($userId);
//        $orderInfo = Db::name('order')->find($orderId);
//        $totalPoint = $orderInfo['total_price'] * $orderInfo['type_id'];
//        $update = [];
//
//
//        //直推
//        $update['direct'] = json_encode(($direct_amounts = $this->calCommissionForDirect($parentId, $totalPoint)));
//        //间推
//        $update['indirect'] = json_encode(($direct_amounts = $this->calCommissionForIndirect($parentId, $totalPoint)));
//        //区代
//        $update['area_agent'] = json_encode($this->calCommissionForAreaAgent($orderId, $totalPoint));
//        //七大战区
//        $update['war_zone'] = json_encode($this->calCommissionForWarZone($totalPoint, $orderInfo['address']));
//        //合伙人
//        $update['partners'] = json_encode($this->calCommissionForPartners($totalPoint));
//
//
//        //级差
//        $update['differential'] = json_encode([]);//json_encode(($differential_amounts = $this->calCommissionForDifferential($totalPrice, $userInfo['parents'])));
//        //全国管委会
//        $update['nationwide'] = json_encode([]);//json_encode($this->calCommissionForNationwide($totalPrice));//json_encode([]);//
//        //战略主席
//        $update['chairman'] = json_encode([]);//json_encode($this->calCommissionForChairman($totalPrice));
//        //直辖市 重庆，上海，天津，北京 1% municipality
//        $update['municipality'] = json_encode([]);//json_encode($this->calCommissionForMunicipality($totalPrice));
//        //法务 1% legal
//        $update['legal'] = json_encode([]);//json_encode($this->calCommissionForLegal($totalPrice));
//        //技术 1% technology
//        $update['technology'] = json_encode([]);//json_encode($this->calCommissionForTechnology($totalPrice));
//        //商学院 2.5% gsb
//        $update['gsb'] = json_encode([]);//json_encode($this->calCommissionForGsb($totalPrice));
//        //运营 2.5% op
//        $update['op'] = json_encode([]);//json_encode($this->calCommissionForOp($totalPrice));
//
//        $update['direct_management_first'] = json_encode([]);//json_encode($update['direct_management_first']);
//        $update['direct_management_second'] = json_encode([]);//json_encode($update['direct_management_second']);
//        $update['differential_management_first'] = json_encode([]);//json_encode($update['differential_management_first']);
//        $update['differential_management_second'] = json_encode([]);//json_encode($update['differential_management_second']);
//
//
//        $update['id'] = $orderId;
////        $update['mission_list'] = json_encode($arr);
//        Db::name('order')->update($update);
//    }
//
//    //直推
//    public function calCommissionForDirect($parentId, $totalPoint)
//    {
//        $directPercent = config('mission.direct.scale');
//        $arr = [];
//        if ((int)$parentId != 0) {
//            $arr[$parentId] = (int)(floor($totalPoint * $directPercent / Web::HUNDRED));
//        }
//        return $arr;
//    }
//
//    //间推
//    public function calCommissionForIndirect($parentId, $totalPoint)
//    {
//        $indirectPercent = config('mission.indirect.scale');
//        $arr = [];
//        if ((int)$parentId != 0) {
//            $parentParent = Db::name('user')->where([
//                'id' => $parentId
//            ])->find();
//            if ((int)$parentParent['pid'] != 0) {
//                $parentParentId = $parentParent['pid'];
//                $arr[$parentParentId] = (int)(floor($indirectPercent * $totalPoint / Web::HUNDRED));
//            }
//        }
//        return $arr;
//    }
//
//    //区代理
//    public function calCommissionForAreaAgent($orderId, $totalPoint)
//    {
//        $orderInfo = \app\model\admin\Order::find($orderId)->toArray();
//        $address = (array)$orderInfo['address'];
//        $arr = [];
//        foreach ([
//                     $address['province_id'] => config('mission.psp.scale'),
//                     $address['city_id'] => config('mission.csp.scale'),
//                     $address['district_id'] => config('mission.dsp.scale')
//                 ] as $area_id => $scale) {
//            //查询代理人
//            if ($agent = Db::name('area_agent')
//                ->alias('a')->field('b.guard_name, b.level, a.user_id')
//                ->join('area b', 'a.area_id=b.id', 'left')
//                ->where('b.id', (int)$area_id)
//                ->find()) {
////                $agent = $agent->toArray();
//                $arr[$agent['user_id']] = (int)(floor($scale * $totalPoint) / Web::HUNDRED);//var_dump($agent);ApiException('404');
//            }
//        }
//        return $arr;
//    }
//
//    //七大战区
//    public function calCommissionForWarZone($totalPoint, $address)
//    {
//        $list = config('mission.war_zone.list');
//        $scale = config('mission.war_zone.scale');
//        $address = (array)json_decode($address);//ApiException(json_encode($address));die;
//        $provinceId = $address['province_id'];//ApiException(json_encode($provinceId));die;
//        $warId = \app\model\admin\Area::where('id', $provinceId)->value('war_id');
//        $userList = $list[$warId];
////        ApiException(json_encode($userList));die;
//        $ponit = bcdiv(bcmul($totalPoint, $scale), (count($userList) * Web::HUNDRED));
//        $arr = [];
//        foreach ($userList as $item) {
//            $arr[$item] = $ponit;
//        }
//        return $arr;
//    }
//
//    //合伙人
//    public function calCommissionForPartners($totalPoint)
//    {
//        $list = config('mission.partners.list');
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.partners.scale');
//            $ponit = bcdiv(bcmul($totalPoint, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//
//    //级差
//    public function calCommissionForDifferential($totalPrice, $parents)
//    {
//        $level = [
//            'no',
//            'manager',
//            'inspector',
//            'director',
//            'partner',
//            'founder'
//        ];
//        $arr = [];
//        $topLevel = 0;
////        var_dump($parents);die;
//        $parents = $parents ? json_decode($parents, true) : [];
//        $parentsArr = $this->getLevelForUser($parents);
////        var_dump($parentsArr);die;
//
//        foreach ($parents as $item) {
//            $cur = $parentsArr[$item];
//            if ($topLevel >= 5) {
//                break;
//            }
//            if ((int)$cur['level_virtual'] > $topLevel) {
//                $scale = config('mission.' . $level[$cur['level_virtual']] . '.scale') - config('mission.' . $level[$topLevel] . '.scale');
////                var_dump($cur['id']);die;
//                $arr[$cur['id']] = (int)(floor($totalPrice * $scale / Web::HUNDRED));
//                $topLevel = $cur['level_virtual'];
//            }
//        }
////        halt($arr);die;
//        return $arr;
//    }
//
//    public function getLevelForUser($parents)
//    {
//        $allUser = $this->getAllItem('user', 'id, level_virtual', $parents);
//        return $allUser;
////        var_dump($allUser);
//    }
//
//    public function getAllItem($table, $str = '', $parents)
//    {
////        var_dump($parents);die;
//        $list = Db::name($table)->field($str)
//            ->where('id', 'in', $parents)
//            ->orderRaw("field(id, " . implode(',', $parents) . ")")
//            ->select();//echo $list;die;
//        $all = [];
//        foreach ($list as $item) {
//            $all[$item['id']] = $item;
////            $all[] = $item;
//        }
//        return $all;
//    }
//
////    //区代理
////    public function calCommissionForAreaAgent($orderId, $totalPrice){
////        $orderInfo = \app\model\admin\Order::find($orderId)->toArray();
////        $address = (array)$orderInfo['address'];//var_dump($address);die;
////        $addressArr = [
////            $address['province_id'],
////            $address['city_id'],
////            $address['district_id']
////        ];
//////        var_dump($addressArr);die;
////        $agentList = Db::name('area_agent')
////            ->alias('a')->field('b.guard_name, b.level, a.user_id')
////            ->join('area b', 'a.area_id=b.id', 'left')
////            ->where('b.id', 'in', $addressArr)
//////            ->fetchSql()
////            ->select()->toArray();//;echo $userModel;die;
////        $arr = [];
////        if(!empty($agentList)){
////            $scaleArr = [
////                2=>config('mission.dsp.scale'),
////                3=>config('mission.csp.scale'),
////                4=>config('mission.psp.scale')
////            ];
//////            var_dump($scaleArr);die;
////            foreach ($agentList as $item){
////                $arr[$item['user_id']] = (int)(floor($scaleArr[$item['level']] * $totalPrice) / Web::HUNDRED);
////            }
////        }
////
////        return $arr;
////    }
//
//
//    //全国管委会
//    public function calCommissionForNationwide($totalPrice)
//    {
//        $list = config('mission.nationwide.list');
//        $scale = config('mission.nationwide.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), count($list));
//        $ponit = (int)(floor($totalPrice * $scale / (count($list) * Web::HUNDRED)));
//        $arr = [];
//        foreach ($list as $item) {
//            $arr[$item] = $ponit;
//        }
//        return $arr;
//    }
//
//
//    //战略主席
//    public function calCommissionForChairman($totalPrice)
//    {
//        $list = config('mission.chairman.list');
////        $scale = config('mission.chairman.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
////        $arr = [];
////        foreach ($list as $item){
////            $arr[$item] = $ponit;
////        }
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.chairman.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    //直辖市 重庆，上海，天津，北京 1%
//    //municipality
//    public function calCommissionForMunicipality($totalPrice)
//    {
//        $list = config('mission.municipality.list');
////        $scale = config('mission.municipality.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
////        $arr = [];
////        foreach ($list as $item){
////            $arr[$item] = $ponit;
////        }
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.municipality.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    //法务 1%
//    //legal
//    public function calCommissionForLegal($totalPrice)
//    {
//        $list = config('mission.legal.list');
////        $scale = config('mission.legal.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
////        $arr = [];
////        foreach ($list as $item){
////            $arr[$item] = $ponit;
////        }
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.legal.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    //技术 1%
//    //technology
//    public function calCommissionForTechnology($totalPrice)
//    {
//        $list = config('mission.technology.list');
////        $scale = config('mission.technology.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
////        $arr = [];
////        foreach ($list as $item){
////            $arr[$item] = $ponit;
////        }
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.technology.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    //商学院 2.5%
//    //gsb
//    public function calCommissionForGsb($totalPrice)
//    {
//        $list = config('mission.gsb.list');
////        $scale = config('mission.gsb.scale');
////        $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
////        $arr = [];
////        foreach ($list as $item){
////            $arr[$item] = $ponit;
////        }
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.gsb.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    //运营 2.5%
//    //op
//    public function calCommissionForOp($totalPrice)
//    {
//        $list = config('mission.op.list');
//        $arr = [];
//        if (!empty($list)) {
//            $scale = config('mission.op.scale');
//            $ponit = bcdiv(bcmul($totalPrice, $scale), (count($list) * Web::HUNDRED));
//            $arr = [];
//            foreach ($list as $item) {
//                $arr[$item] = $ponit;
//            }
//        }
//        return $arr;
//    }
//
//    public function calCommissionForDifferentialManagements($user_id, $amount, $scale, $level = 0)
//    {
//        //初始化奖金
//        $compute_user_id = $computed_amount = 0;
//        //查询当前用户父级结构
//        if ($parents = Db::name('user')->where('id', (int)$user_id)->value('parents')) {
//            //循环父级结构
//            foreach (json_decode($parents, true) as $k => $parent_id) {
//                //判断层级
//                if ((int)$k === (int)$level) {
//                    //计算奖项
//                    $compute_user_id = (int)$parent_id;
//                    $computed_amount = bcdiv(bcmul($amount, $scale), Web::HUNDRED);
//                }
//            }
//        }
//        return (int)$compute_user_id > 0 ? ['user_id' => (int)$compute_user_id, 'amount' => (int)$computed_amount] : false;
//    }
//
//    //直推间推一代管理奖
//    public function calCommissionForDirectManagementFirst($direct)
//    {
//        $arr = [];
//        if ($directList = json_decode($direct, true)) {
//            $direct_user_id = $indirect_user_id = 0;
//            $direct_user_scale = $indirect_user_scale = (int)config('mission.management1.scale');
//            //循环只推间推奖
//            foreach (array_keys($directList) as $k => $user_id) {
//                if ((int)$k === 0) {
//                    $direct_user_id = (int)$user_id;
//                } else {
//                    $indirect_user_id = (int)$user_id;
//                }
//            }
//            //判断直推是否有效
//            if ((int)$direct_user_id > 0) {
//                //计算直推管理奖
//                $arr[$direct_user_id] = bcdiv(bcmul($directList[$direct_user_id], $direct_user_scale), Web::HUNDRED);
//            }
//            //判断间推是否有效
//            if ((int)$indirect_user_id > 0) {
//                //计算直推管理奖
//                $arr[$indirect_user_id] = bcdiv(bcmul($directList[$indirect_user_id], $indirect_user_scale), Web::HUNDRED);
//            }
//        }
//        return $arr;
//    }
//
//    //直推间推二代管理奖
//    public function calCommissionForDirectManagementSecond($direct)
//    {
//        $management2Scale = config('mission.management2.scale');
//        $directList = json_decode($direct, true);//var_dump($directList);die;//[10008]=>int(4000)[10005]=>int(2000)
//
//        $newDirectList = $this::getAllUserForArr($directList);//var_dump($newDirectList);die;
//        $arr = [];
//        foreach ($newDirectList as $key1 => $item1) {
//            $directArr = json_decode($item1, true);
//            if (isset($directArr[1])) {
////                isset($directArr[0]) && !empty($directArr[0])
//                $arr[$directArr[1]] = bcdiv(bcmul($directList[$key1], $management2Scale), Web::HUNDRED);
//            }
//        }
////        var_dump($arr);die;
//        return $arr;
//    }
//
//    //级差一代管理奖
//    public function calCommissionForDifferentialManagementFirst($differential)
//    {//var_dump($differential);die;
//        $management1Scale = config('mission.management1.scale');
//        $differentialList = json_decode($differential, true);
////var_dump($differentialList);die;
//        $newDifferentialList = $this::getAllUserForArr($differentialList);
//        $arr = [];
//        foreach ($newDifferentialList as $key1 => $item1) {
////            var_dump($item1);die;//[10002,10001,10000]
//            $differentialArr = json_decode($item1, true);//var_dump($differentialArr);die;
////            echo $differentialList[$key1];die;
//            if (isset($differentialArr[0])) {
//                $arr[$differentialArr[0]] = bcdiv(bcmul($differentialList[$key1], $management1Scale), Web::HUNDRED);
//            }
//        }
////        var_dump($arr);die;
//        return $arr;
//    }
//
//
//    //级差二代管理奖
//    public function calCommissionForDifferentialManagementSecond($differential)
//    {
//        $management2Scale = config('mission.management2.scale');
//        $differentialList = json_decode($differential, true);
//
//        $newDifferentialList = $this::getAllUserForArr($differentialList);
//        $arr = [];
//        foreach ($newDifferentialList as $key1 => $item1) {
//            $differentialArr = json_decode($item1, true);
//            if (isset($differentialArr[1])) {
//                $arr[$differentialArr[1]] = bcdiv(bcmul($differentialList[$key1], $management2Scale), Web::HUNDRED);
//            }
//        }
////        var_dump($arr);die;
//        return $arr;
//    }
//
//    public static function getAllUserForArr($arr)
//    {//var_dump($arr);//die;
//        $newArr = array_keys($arr);//var_dump($newArr);die;[10008,10005]
//        $userList = Db::name('user')->where('id', 'in', $newArr)->column('parents', 'id');
////        $userListArr = [];
////        foreach ($newArr as $item1){
////            foreach ($userList as $item2){
////                if($item1 == $item2['id']){
////                    $userListArr[] = $item2;
////                    break;
////                }
////
////            }
////        }
////        return $userListArr;
//        return $userList;
////        var_dump($userList);die;
//    }
//
//    //发放佣金
//    public function grantCommission($orderId, $userId)
//    {
//        $orderCommissionList = Db::name('order')->field('direct, indirect, area_agent, war_zone, partners')->find($orderId);
//
//        $update = [];
//        $remarkArr = [
//            'direct' => '直推',
//            'indirect' => '间推',
//            'area_agent' => '地区代理',
//            'war_zone' => '七大区运营中心',
//            'partners' => '合伙人',
//
////            'differential'=>'级差',
////            'nationwide'=>'全国管委会',
////            'chairman'=>'战略主席',
////            'municipality'=>'直辖市',
////            'legal'=>'法务',
////            'technology'=>'技术',
////            'gsb'=>'商学院',
////            'op'=>'运营',
////            'direct_management_first'=>'直推间推一代管理奖',
////            'direct_management_second'=>'直推间推二代管理奖',
////            'differential_management_first'=>'级差一代管理奖',
////            'differential_management_second'=>'级差二代管理奖',
//        ];
//        //ApiException('404');
//        // TODO(yanchao): +transaction, UserWallet修改+order修改需要一致性保障
//        $type = 3;
//        foreach ($orderCommissionList as $key1 => $item) {
//            $arr = json_decode($item, true);
//            foreach ($arr as $key2 => $item2) {
//                //induce($userId, $amount, $type, $objectId, $source = 0, $remark = '', $isRecharge = false)
//                \app\model\common\UserWallet::induce($key2, $item2, $type, $orderId, 0, "【订单奖励】" . $remarkArr[$key1] . "积分");
//            }
//        }
//        //是专区商品 立刻更新订单状态
//        Db::name('order')->update(['id' => $orderId, 'is_grant' => 1]);
//        Db::name('user')->update(['id' => $userId, 'activation' => 1, 'last_order_time' => time()]);
//    }
//
//    public function getAllItems($table, $str = '', $id)
//    {
//        $list = Db::name($table)->field($str)
//            ->select();
//        $all = [];
//        foreach ($list as $item) {
//            $all[$item[$id]] = $item;
//        }
//        return $all;
//    }
//
//    //减少余额
//    public function decBalance($userId, $totalPrice, $orderId)
//    {
//        $orderItem = \app\model\admin\OrderItem::with(['goodsItem' => function ($query) {
//            $query->field('type_id,id,is_scm');
//        }])->field('id, order_id, goods_id')
//            ->where('order_id', $orderId)->find()->toArray();
//
//        $userWallet = \app\model\common\UserWallet::where('user_id', $userId)->find()->toArray();
////        var_dump($orderItem);die;
//        $typeId = $orderItem['goods_item']['type_id'];
//        $isScm = $orderItem['goods_item']['is_scm'];
//
//        //操作余额
//        $updateBalance['id'] = $userWallet['id'];
//        $updateBalance['user_id'] = $userId;
//        $updateBalance['balance'] = $userWallet['balance'] - $totalPrice;
//        $updateBalance['amount'] = $totalPrice;
//        $updateBalance['fee_amount'] = $updateBalance['balance'];
//        $updateBalance['type'] = 2;
//        $updateBalance['mode'] = 0;
//        $updateBalance['object_id'] = $orderId;
//        $updateBalance['remark'] = "消费金额";
//
//        //操作省心值
//        $point = $totalPrice * $typeId;
//        $updatePoint['id'] = $userWallet['id'];
//        $updatePoint['user_id'] = $userId;
//        if ($isScm) {
//            //供应链
//            $updatePoint['locking_point'] = $userWallet['locking_point'] + $point;
//            $updatePoint['fee_amount'] = $updatePoint['locking_point'];
//        } else {
//            $updatePoint['point'] = $userWallet['point'] + $point;
//            $updatePoint['fee_amount'] = $updatePoint['point'];
//        }
//
//        $updatePoint['amount'] = $point;
//
//        $updatePoint['type'] = 3;
//        $updatePoint['mode'] = 1;
//        $updatePoint['object_id'] = $orderId;
//        $updatePoint['remark'] = "消费得省心值";
//
////        halt([
////            $updateBalance,
////            $updatePoint
////        ]);
//        $userWallet = new UserWallet();
//        trace('[购物减少余额]:' . json_encode($updatePoint), 'error');
//        $res = $userWallet->allowField(['user_id', 'point', 'balance', 'locking_point'])->saveAll([
//            $updateBalance,
//            $updatePoint
//        ]);
//        return $res;
//    }
//
//    //购物增加省心值
//    public static function addUserPoint($order)
//    {
//        $userId = $order->user_id;
//        $orderId = $order->id;
//        $typeId = $order->type_id;
//        $totalPrice = $order->total_price;
//        //操作省心值
//        $point = (int)$totalPrice * (int)$typeId;
//
//        \app\model\common\UserWallet::induce($userId, $point, 3, $orderId, 0, false, "消费得省心值");
//    }


}